package com.movie.controller;

import com.movie.model.Order;
import com.movie.model.OrderSeat;
import com.movie.model.User;
import com.movie.service.OrderService;
import com.movie.util.OrderRequest;
import com.movie.util.OrderStatistics;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;

    @PostMapping("/create")
    @ResponseBody
    public String createOrder(@RequestBody OrderRequest request, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "error";
        }

        try {
            Integer orderId = orderService.createOrder(user.getId(), request);
            return orderId.toString(); // 返回订单ID而不是"success"
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
    }

    @GetMapping("/seats/{screeningId}")
    @ResponseBody
    public List<OrderSeat> getScreeningSeats(@PathVariable Integer screeningId) {
        return orderService.getScreeningSeats(screeningId);
    }

    @GetMapping("/user/orders")
    @ResponseBody
    public List<Order> getUserOrders(HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return new ArrayList<>();
        }
        return orderService.getUserOrders(user.getId());
    }

    @GetMapping("/statistics")
    @ResponseBody
    public OrderStatistics getOrderStatistics() {
        return orderService.getOrderStatistics();
    }

    @PostMapping("/pay/{orderId}")
    @ResponseBody
    public String processPayment(@PathVariable Integer orderId, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "error";
        }

        try {
            boolean success = orderService.processPayment(orderId);
            return success ? "success" : "error";
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
    }
}